/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> levelOrder(TreeNode* root)
    {
        if (root == nullptr) return {};

        queue<TreeNode*> q1, q2;
        vector<vector<int>> ret;
        vector<int> tmp;
        q1.push(root);

        while (!q1.empty() || !q2.empty())
        {
            TreeNode* cur = nullptr;
            while (!q1.empty())
            {
                cur = q1.front();
                tmp.push_back(cur->val);
                if (cur->left != nullptr)q2.push(cur->left);
                if (cur->right != nullptr)q2.push(cur->right);
                q1.pop();
            }
            if (!tmp.empty()) ret.push_back(move(tmp));

            while (!q2.empty())
            {
                cur = q2.front();
                tmp.push_back(cur->val);
                if (cur->left != nullptr)q1.push(cur->left);
                if (cur->right != nullptr)q1.push(cur->right);
                q2.pop();
            }
            if (!tmp.empty()) ret.push_back(move(tmp));
        }
        return ret;
    }
};